package com.shop.apigateway.filter;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_DECORATION_FILTER_ORDER;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.shop.apigateway.util.CookieUtil;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

/**
 * 买家拦截
 *
 * @author denpeng
 * @create 2018-05-22 11:15
 **/
@Component
public class AuthBuyerFilter extends ZuulFilter {

  private final StringRedisTemplate redisTemplate;

  @Autowired
  public AuthBuyerFilter(StringRedisTemplate redisTemplate) {
    this.redisTemplate = redisTemplate;
  }

  @Override
  public String filterType() {
    return PRE_TYPE; //pre
  }

  @Override
  public int filterOrder() {
    return PRE_DECORATION_FILTER_ORDER - 1; //比prefilter小
  }

  @Override
  public boolean shouldFilter() {
    RequestContext requestContext = RequestContext.getCurrentContext();
    HttpServletRequest request = requestContext.getRequest();
    return "/order/order/create".equals(request.getRequestURI());
  }

  @Override
  public Object run() throws ZuulException {
    RequestContext requestContext = RequestContext.getCurrentContext();
    HttpServletRequest request = requestContext.getRequest();
    //买家
      Cookie cookie = CookieUtil.get(request, "openid");
      if (cookie == null || StringUtils.isBlank(cookie.getValue())) {
        requestContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
        requestContext.setSendZuulResponse(false);
      }

    return null;
  }
}
